{{>licenseInfo}}

import http from "k6/http";
import { group, check, sleep } from "k6";

const BASE_URL = "{{baseURL}}";
{{#authToken}}
const TOKEN = "TOKEN_VALUE_HERE";
{{/authToken}}
// Sleep duration between successive requests.
// You might want to edit the value of this variable or remove calls to the sleep function on the script.
const SLEEP_DURATION = 0.1;
// Global variables should be initialized.
{{#extra}}
let {{{key}}} = "TODO_EDIT_THE_{{{value}}}";
{{/extra}}

export default function() {
    {{#requestGroups}}
    group("{{{groupName}}}", () => {
        {{#variables}}
        let {{{key}}} = {{#lambda.handleParamValue}}{{value}}{{/lambda.handleParamValue}}
        {{/variables}}
        {{#requests}}

        // Request No. {{-index}}: {{{operationId}}}
        {
            let url = BASE_URL + `{{{path}}}{{=<% %>=}}<%#query%><%#-first%>?<%/-first%><%& key%>=<%& value%><%^-last%>&<%/-last%><%/query%><%={{ }}=%>`;
            {{#body}}
            {{^hasBodyExample}}
            // TODO: edit the parameters of the request body.
            {{/hasBodyExample}}
            let body = {{#body}}{{=<% %>=}}{<%#parameters%>"<%& key%>": <%& value%><%^-last%>, <%/-last%><%/parameters%>}<%={{ }}=%>{{/body}};
            {{/body}}
            {{#params}}
            let params = {{#params}}{{=<% %>=}}{
                headers: {
                    <%# headers%>"<%& key%>": <%& value%><%^-last%>, <%/-last%><%/headers%><%#responseType%>, "Accept": <%& responseType%><%/responseType%>
                }<%#hasCookie%>, cookies: {
                    <%# cookies%>"<%& key%>": <%& value%><%^-last%>, <%/-last%><%/cookies%>
                }<%/hasCookie%><%# auth%>, auth: "<%& auth%>"<%/auth%>
            }<%={{ }}=%>{{/params}};
            {{/params}}
            {{#isDelete}}
            {{#params}}
            // this is a DELETE method request - if params are also set, empty body must be passed
            let request = http.{{method}}(url, {} {{#params}}, params{{/params}});
            {{/params}}
            {{^params}}
            let request = http.{{method}}(url);
            {{/params}}
            {{/isDelete}}
            {{^isDelete}}
            let request = http.{{method}}(url{{#body}}, JSON.stringify(body){{/body}}{{#params}}, params{{/params}});
            {{/isDelete}}

            {{#k6Checks}}
            {{=<% %>=}}
            check(request, {
                "<%& description%>": (r) => r.status === <%& status%>
            });
            <%={{ }}=%>
            {{/k6Checks}}
            {{#dataExtract}}

            {{{paramName}}} = JSON.parse(request.body).{{{valuePath}}}; // extract data for subsequent use
            {{/dataExtract}}
            {{^-last}}

            sleep(SLEEP_DURATION);
            {{/-last}}
        }
        {{/requests}}
    });

    {{/requestGroups}}
}
